package com.dfbz;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dfbz.entity.User;
import com.dfbz.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@SpringBootTest(classes = MyBatisPlusApplication.class)
@RunWith(SpringRunner.class)
public class Demo05_UpdateWrapper {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test1() throws Exception {
        UpdateWrapper<User> wrapper = Wrappers.update();

        // UpdateWrapper也是AbstractWrapper的子类,因此也具备一些基本的查询方法
        wrapper.like("name", "J");

        List<User> userList = userMapper.selectList(wrapper);

        for (User user : userList) {
            System.out.println(user);
        }

    }


    /**
     * 第一种方法: 使用wrapper来修改,并且指定查询条件
     *
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {
        UpdateWrapper<User> wrapper = Wrappers.update();
        wrapper.set("name", "Jackson");
        wrapper.set("age", "16");
        wrapper.set("sex", "1");
        wrapper.eq("id", 2L);

        // SQL: UPDATE user SET name=?, sex=?, age=? WHERE (id = ?)
        userMapper.update(null, wrapper);
    }


    /**
     * 第二种方法: 使用wrapper来封装条件,使用entity来封装修改的数据
     *
     * @throws Exception
     */
    @Test
    public void test3() throws Exception {
        UpdateWrapper<User> wrapper = Wrappers.update();
        wrapper.eq("id", 2L);

        User user = new User(null, "Jack", "0", 28);

        // SQL: UPDATE user SET name=?, sex=?, age=? WHERE (id = ?)
        userMapper.update(user, wrapper);

    }

    /**
     * 第三种方法: Wrappers.update(user)传递查询的条件,使用wrapper来修改
     *
     * @throws Exception
     */
    @Test
    public void test4() throws Exception {
        User user = new User();
        user.setId(1L);

        // user当做查询条件
        UpdateWrapper<User> wrapper = Wrappers.update(user);
        wrapper.set("name", "xiaohui");
        wrapper.set("sex", "0");
        wrapper.set("age", "22");

        // SQL : UPDATE user SET name=?,sex=?,age=? WHERE id=?
        userMapper.update(null, wrapper);
    }

    /**
     * setSql方法
     *
     * @throws Exception
     */
    @Test
    public void test5() throws Exception {
        UpdateWrapper<User> wrapper = Wrappers.update();
        wrapper.setSql("name='abc',sex='0',age=18 where id=1");

        // SQL: UPDATE user SET name='abc',sex='0',age=18 where id=1
        userMapper.update(null, wrapper);
    }
}
